package com.example.user.service.impl;

import com.example.commons.config.jwt.JwtBuild;
import com.example.commons.entity.Users;
import com.example.commons.exception.BusinessException;
import com.example.commons.util.PageConverterUtil;
import com.example.commons.util.UserUtil;
import com.example.commons.vo.UserVo;
import com.example.user.service.LoginService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.time.temporal.ChronoUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    @Trace
    @Tag(key = "list",value = "String")
    public String[] login(String username, String password) {
        UsernamePasswordAuthenticationToken userToken =
                new UsernamePasswordAuthenticationToken(username, password);
        //此处经过一系类内部类后会调用至UserDetailsService的load方法
        //load方法的入参name就是token里的name
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(userToken);
        } catch (AuthenticationException a) {
            a.printStackTrace();
            throw new BusinessException("登录失败，账号/密码有误");
        }
        Users users = (Users) authentication.getPrincipal();
        users.setPassword(null);
        UserVo userVo = PageConverterUtil.copyProperty(users, UserVo.class);
        UserUtil.put(userVo);
        JwtBuild jwtBuild = new JwtBuild(false,null);
        String token = jwtBuild.getToken(users.toString(), 24, ChronoUnit.HOURS);
        return new String[]{token, users.getId()};
    }
}
